/**
 * @description
 * @author ybjuejue
 * @createDate 2019/1/4/004
 */
;(function (_) {
    var clock = {
        open: function (url, data, opt) {
            if (_.platform.CMPShell) {
                _.href.openWebViewCatch = function () {
                    return 1
                }
            }
            if (url) {
                _.href.next(url, data || null, opt || {nativeBanner: false})
            }
        },
        load: function (url, data, opt) {
            if (_.platform.CMPShell) {
                _.href.openWebViewCatch = function () {
                    return 0
                }
            }
            if (url) {
                _.href.next(url, data || null, opt || {nativeBanner: false})
            }
        },
        path: {
            outclock: getPath('/html/outclock.html'),
            clockMonthDetail: getPath('/html/clock-month-detail.html'),
            clockDayDetail: getPath('/html/clock-day-detail.html'),
            clockPersonMonthDetail: getPath('/html/clock-person-month-detail.html')
        },
        getPath: getPath,
        life: extendCmpLife,
        sdk: serve(),
        checkShowPage: checkShowPage,
        getDate: dealTime,
        components: {},
        getHrefParam: getHrefParam,
        hrefParams: getHrefParam(window.location.href),
        clockTypeMap: {
            missingClock: '缺卡',
            normal: '正常',
            outside: '外勤',
            late: '迟到',
            leaveEarly: '早退',
        },
    };


    /* html 全局组件*/
    clock.life('html', {
        $onloaded: function () {
            document.addEventListener('com.seeyon.m3.phone.webBaseVC.didDisAppear', function () {
                clock.checkShowPage(true)
            });
            document.addEventListener('com.seeyon.m3.phone.webBaseVC.didAppear', function () {
                clock.checkShowPage()
            });
            this.addEvent();
        },
        methods: {
            addEvent: function () {
                var backBtn = this.$dom.find('#backBtn');
                if (backBtn) {
                    backBtn.on('tap', function () {
                        _.href.back();
                    })
                }
                _.backbutton();
                _.backbutton.push(function () {
                    _.href.back();
                });
            }
        }
    });

    /* 时间格式处理*/
    function dealTime(val) {
        var date = val ? /-|:/g.test(val) ? new Date(val.replace(/-/g, "/")) : new Date(parseInt(val)) : new Date();
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var h = date.getHours();
        var t = date.getMinutes();
        var w = date.getDay() + 1;
        var dd = d < 10 ? '0' + d : '' + d;
        var mm = m < 10 ? '0' + m : '' + m;
        var hh = h < 10 ? '0' + h : '' + h;
        var tt = t < 10 ? '0' + t : '' + t;
        var weekDay = [cmp.i18n("Attendance.label.sunday"), cmp.i18n("Attendance.label.monday"), cmp.i18n("Attendance.label.tuesday"), cmp.i18n("Attendance.label.wednesday"), cmp.i18n("Attendance.label.thursday"), cmp.i18n("Attendance.label.friday"), cmp.i18n("Attendance.label.saturday")];
        return {
            year: y,
            month: m,
            day: d,
            week: w,
            hours: h,
            minutes: t,
            hh: hh,
            tt: tt,
            mm: mm,
            dd: dd,
            time: date.getTime(),
            weekday: weekDay[w - 1],
            hoursTime: date.format("hh:mm"),
            fullDate: date.format(cmp.i18n("Attendance.label.date")),
            today: date.format("yyyy-MM-dd"),
            monthDate: date.format("MM-dd"),
            fullMonth: date.format("yyyy-MM")
        }
    }

    /* 编译cmp 和 当前项目路径*/
    function getPath(url, type) {
        var baseUrl = type ? cmpPath : attendancePath;
        return baseUrl + url;
    }

    /* 对原有的cmp.life 进行属性扩展*/
    function extendCmpLife(el, opt) {
        var dom = $cmp(el);
        var isPage = dom && dom.hasClass('page-view') ? true : false;
        var onload = typeof opt.$onloaded === 'function' ? opt.$onloaded : function () {
        };
        opt.$onloaded = function () {
            this.$isloaded = true;
            if (this.$isPageShow || !isPage) {
                onload.call(this);
                this.$isinit = true
            }
        };
        var life = _.life(el, opt);
        life.dialogTemp = null;
        life.$inject = injectApi;
        life.$dialog = dialog;
        if ('$onPageHiddenShow' in opt) {
            life['$onPageHiddenShow'] = opt['$onPageHiddenShow']
        }
        el && (life.$dom = $cmp(el));
        this.components[el] = life;

        function injectApi(callback) {
            var api = Object.prototype.toString.call(opt.$componentNeedApi) === '[object Object]' ? opt.$componentNeedApi : {};
            var js = api.js || [], css = api.css || [];
            _.asyncLoad.css(css);
            _.asyncLoad.js(js, function () {
                callback && callback();
            });
        };
        function dialog(opt) {
            showLoading(this, false);
            this.dialogTemp = null;
            if (typeof opt === 'object') {
                _.dialog.loading(opt);
                var dom = $cmp(opt.dom);
                if (dom[0]) {
                    var cmpLoading = dom.find('.cmp-loading');
                    if (cmpLoading[0]) {
                        var staticLoading = cmpLoading[0].outerHTML;
                        this.dialogTemp = {
                            html: staticLoading,
                            dom: dom
                        }
                    }
                }
                _.dialog.loading(false);
                showLoading(this, true);
            } else {
                _.dialog.loading(opt)
            }

        }
    }
    function showLoading(component,status) {
        var dialogTemp = component.dialogTemp;
        if (dialogTemp) {
            if (dialogTemp.dom && dialogTemp.dom) {
                var loading = dialogTemp.dom.find('.cmp-loading');
                if (loading) {
                    loading.remove()
                }
                status&&dialogTemp.dom.append(dialogTemp.html);
            }
        }
    }
    /*获取url地址栏参数*/

    function getHrefParam(str) {
        try {
            var url = decodeURI(str || '');
            url = url.split('?')[1];
            url = url.replace(/=/g, '":"');
            url = url.replace(/&/g, '","');
            url = url.replace('?', '');
            url = url.replace(/#\S*/g, '')
            url = '{"' + url + '"}';
        } catch (e) {
            return {};
        }
        return JSON.parse(url);
    }

    /*对所有页面及组件 添加显示隐藏回调*/
    function checkShowPage(hidden) {
        $cmp('.page-view').each(function () {
            var component = clock.components['#' + this.id + ''];
            var isShow = hidden ? false : (this.offsetHeight > 0);
            if (component) {
                var status = Boolean(component.$isPageShow);
                if ((!status && isShow)) {
                    showLoading(component, isShow);
                    setPageStatus(component, isShow);
                } else if (status && !isShow) {
                    setPageStatus(component, isShow)
                }
            }
        });

        function setPageStatus(life, s) {
            var component = life || {};
            component.$isPageShow = s;
            if (s) {
                component.$inject();
            }
            if (typeof component.$onPageHiddenShow === 'function' && component.$isinit) {
                component.$onPageHiddenShow(s);
            }
            if (s && !component.$isinit && component.$isloaded) {
                component.$onloaded();
            }
        }
    }

    /*接口地址存放*/
    function serve() {
        return {
            getAuthInfo: function (options) {
                /*用户权限数据*/
                return $s.Rest.get('attendance/config', '', '', cmp.extend({}, options))
            },
            getMapInfo: function (options) {
                /*打卡地图数据*/
                return $s.Rest.get('attendance/mapData', '', '', cmp.extend({}, options))
            },
            getIndexClockInfo: function (options) {
                /*打卡首页数据*/
                return $s.Rest.get('attendance/punchInfo', '', '', cmp.extend({}, options))
            },
            getUserMonthData: function (time, options) {
                /*个人统计列表首页*/
                return $s.Rest.get('attendance/personalStats/' + time, '', '', cmp.extend({}, options))
            },
            getUserOneDayData: function (time, options) {
                /*个人月历数据接口*/
                return $s.Rest.get('attendance/m3DayCarQuery/' + time, '', '', cmp.extend({}, options))
            },
            getUserTopList: function (time, num, options) {
                /*个人每日排行榜数据*/
                return $s.Rest.get('attendance/arriveEarlyQuery' + (time ? '/' + time : '') + (num ? '/' + num : ''), '', '', cmp.extend({}, options))
            }
        }
    }

    /*导出20190330版本打卡基本代码*/
    window.$clock = clock;
})(cmp);